using System.Collections.Generic;
using UnityEngine;

namespace Function.SkillEditor.Runtime
{
    public class AudioRender
    {
        private static Dictionary<GameObject, List<AudioSource>> _audioSources =
            new Dictionary<GameObject, List<AudioSource>>();

        public static AudioSource GetAudioByGameObject(GameObject go)
        {
            var audioSource = go.AddComponent<AudioSource>();
            if (!_audioSources.TryGetValue(go, out var audioSources))
            {
                audioSources = new List<AudioSource>();
                _audioSources.Add(go, audioSources);
            }

            audioSources.Add(audioSource);
            return audioSource;
        }

        public static void RemoveAudioByGameObject(GameObject go, AudioSource audioSource)
        {
            if (_audioSources.TryGetValue(go, out var audioSources))
            {
                audioSources.Remove(audioSource);
            }

            Object.DestroyImmediate(audioSource);
        }

        public static AudioSource PlayAudio(GameObject go, AudioClip clip)
        {
            var audio = GetAudioByGameObject(go);
            audio.clip = clip;
            audio.Play();
            return audio;
        }

        public static void StopAudio(GameObject go, AudioSource audioSource)
        {
            RemoveAudioByGameObject(go, audioSource);
        }
    }
}